package com.mbbb.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mbbb.yygh.client.cmn.DictFeignClient;
import com.mbbb.yygh.common.result.R;
import com.mbbb.yygh.enums.DictEnum;
import com.mbbb.yygh.hosp.repository.HospitalRepository;
import com.mbbb.yygh.hosp.service.HospitalService;
import com.mbbb.yygh.model.hosp.BookingRule;
import com.mbbb.yygh.model.hosp.Hospital;
import com.mbbb.yygh.vo.hosp.HospitalQueryVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    //根据医院编号获取医院预约挂号详情
    @Override
    public Map<String, Object> findHospDetail(String hoscode) {
        //最后封装
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(hospitalRepository.findByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());

        return result;
    }

    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findHospListByHosname(String hosname) {

        List<Hospital> list = hospitalRepository.findByHosnameLike(hosname);

        return list;
    }

    //条件查询医院列表
    @Override
    public List<Hospital> findHospListQuery(HospitalQueryVo hospitalQueryVo) {

        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //封装条件
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        Example<Hospital> example = Example.of(hospital,matcher);

        //调用方法
        List<Hospital> hospitalList = hospitalRepository.findAll(example, sort);

        //取编号对应的名称
        hospitalList.stream().forEach(item -> {
            this.packHospital(item);
        });

        return hospitalList;
    }

    //根据医院编号获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        String hosname = hospital.getHosname();
        return hosname;
    }

    //获取医院详情
    @Override
    public Map<String, Object> showDetail(String id) {
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        //获取预约规则
        BookingRule bookingRule = hospital.getBookingRule();

        HashMap<String, Object> result = new HashMap<>();
        result.put("hospital",hospital);
        result.put("bookingRule",bookingRule);

        return result;
    }

    //更新医院上线状态功能
    @Override
    public void updateHospStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    //医院列表（带分页）
    @Override
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //设置排序
        Sort sort = Sort.by(Sort.Direction.DESC,"createTime");
        //设置分页
        //0为第一页（当前页）
        PageRequest pageRequest = PageRequest.of(page-1,limit,sort );
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        Hospital hospital = new Hospital();
        //有查询条件时自动封装条件，没有时不封装（自动）
        BeanUtils.copyProperties(hospitalQueryVo,hospital);

        //封装条件
        Example example = Example.of(hospital,matcher);

        //调用方法
        Page<Hospital> pages = hospitalRepository.findAll(example, pageRequest);

        //从分页对象pages中获取List集合,遍历集合
        //得到每个医院对象，获取编号
        //根据编号远程调用的到名称
        /*List<Hospital> list = pages.getContent();
        for (Hospital hosp : list) {

        }*/
        pages.getContent().stream().forEach(hosp ->{
            this.packHospital(hosp);
        });

        return pages;
    }

    //获取Hospital对象的所有编号，把编号对应的名称获取，完成封装
    private Hospital packHospital(Hospital hospital) {
        //1.获取所有编号
        String hostype = hospital.getHostype(); //医院等级
        String provinceCode = hospital.getProvinceCode(); //省编号
        String cityCode = hospital.getCityCode(); //市编号
        String districtCode = hospital.getDistrictCode(); //区编号

        //2.远程调用方法获取编号对应名称
        String hostypeClient = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hostype);
        String provinceClient = dictFeignClient.getName(provinceCode);
        String cityClient = dictFeignClient.getName(cityCode);
        String districtClient = dictFeignClient.getName(districtCode);

        //3.完成封装
        hospital.getParam().put("hostypeClient", hostypeClient);
        hospital.getParam().put("fullAddress", provinceClient + cityClient + districtClient + hospital.getAddress());

        return hospital;
    }

    //根据医院系统传递来的医院编号查询医院信息
    @Override
    public Hospital getHospHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    //把map集合数据添加到mongodb数据库中
    @Override
    public void saveHosp(Map<String, Object> stringObjectMap) {

        //1. save方法的参数是Hospital对象，stringObjectMap集合 --> Hospital对象
        //1.1 把map变成json字符串
        String jsonString = JSONObject.toJSONString(stringObjectMap);
        //1.2 把json字符串转换成Hospital对象
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        //2. 根据医院编号查询医院信息是否已经添加（hoscode唯一）
        Hospital existHospital = hospitalRepository.findByHoscode(hospital.getHoscode());

        //如果已经添加过，修改（需要id）
        if (existHospital != null) {
            //设置id
            hospital.setId(existHospital.getId());
            //添加时间
            hospital.setCreateTime(existHospital.getCreateTime());
            //修改时间
            hospital.setUpdateTime(new Date());
            //设置医院状态
            hospital.setStatus(0);
            //调用方法
            hospitalRepository.save(hospital);
        } else { //如果没有添加，进行添加操作
            //添加时间
            hospital.setCreateTime(new Date());
            //修改时间
            hospital.setUpdateTime(new Date());
            //设置医院状态
            hospital.setStatus(0);
            //调用方法
            hospitalRepository.save(hospital);
        }
    }
}
